﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using DAL;
using System.Text;

namespace PeisongWeb.admin
{
    public partial class DynamicOrderList : adminPage
    {
        protected int id
        {
            get
            {
                int tmp;
                try { tmp = Convert.ToInt32(ViewState["id"]); }
                catch { tmp = 0; }
                return tmp;
            }
            set
            { ViewState["id"] = value; }
        }
        protected bool isUnderTransfer = false;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (hasPermission("DH", 1))
                {
                    rptBind();
                }
                else
                {
                    Library.Script.ClientMsgUrl("没有权限！", "index.aspx");
                    return;
                }

            }
        }
        void rptBind()
        {
            StringBuilder where = new StringBuilder();
            where.Append("1=1");
            if (!string.IsNullOrEmpty(ddlDynamicStatus.SelectedValue))
                where.AppendFormat(" and [status]='{0}'", ddlDynamicStatus.SelectedValue);
            if (!string.IsNullOrEmpty(txt_company.Text))
                where.AppendFormat(" and [company] like '%{0}%'", txt_company.Text);
            if (!string.IsNullOrEmpty(txt_orderNo.Text))
                where.AppendFormat(" and orderNo='{0}'", txt_orderNo.Text);
            if (!string.IsNullOrEmpty(txt_ProName.Text))
                where.AppendFormat(" and orderId in (select DISTINCT orderId from dbo.vw_DynamicOrderItem_list where [name] like '%{0}%')", txt_ProName.Text);
            if (ext_StartInputDt.SelectedDate != DateTime.MinValue)
                where.AppendFormat(" and datediff(day,[orderDt],'{0}')<=0", ext_StartInputDt.Value.ToString());
            if (ext_EndInputDt.SelectedDate != DateTime.MinValue)
                where.AppendFormat(" and datediff(day,[orderDt],'{0}')>=0", ext_EndInputDt.Value.ToString());
            if (ext_startReceiveDt.SelectedDate != DateTime.MinValue)
                where.AppendFormat(" and datediff(day,[receiveDt],'{0}')<=0", ext_startReceiveDt.Value.ToString());
            if (ext_endReceiveDt.SelectedDate != DateTime.MinValue)
                where.AppendFormat(" and datediff(day,[receiveDt],'{0}')>=0", ext_endReceiveDt.Value.ToString());

            DataSet ds = logic.order.selectDynamicOrder(where.ToString(), "orderid desc", AspNetPager1.PageSize, AspNetPager1.CurrentPageIndex);
            AspNetPager1.RecordCount = Convert.ToInt32(ds.Tables[0].Rows[0][0]);
            rpt_list.DataSource = ds.Tables[1];
            rpt_list.DataBind();
        }
        protected void AspNetPager1_PageChanged(object sender, EventArgs e)
        {
            rptBind();
        }
        protected void lbtn_Search_Click(object sender, EventArgs e)
        {
            AspNetPager1.CurrentPageIndex = 1;
            rptBind();
        }

        protected void rpt_list_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            if (e.CommandName == "details")
            {
                id = Convert.ToInt32(e.CommandArgument);
                getDetails(id);
                rtpDobind(id);
                dynamicorder_details.Show();
            }
        }

        protected void getDetails(int orderid)
        {

            DataSet ds = logic.order.selectDynamicOrder("orderid=" + orderid, "orderid", 1, 1);
            DataRow dr = ds.Tables[1].Rows[0];
            ddl_receiveTime.DataSource = logic.sysCode.receiveTime();
            ddl_receiveTime.DataBind();
            lbl_StandardAmount.Text = string.Format("{0:F2}", dr["amount"].ToString());
            txt_status.Text = dr["orderStatus"].ToString();
            lbl_Note.Text = dr["note"].ToString();
            lbl_OrderNo.Text = "临时订单编号：" + dr["orderid"].ToString();
            lbl_orderDt.Text = dr["orderDt"].ToString();
            txt_serviceNote.Text = dr["serviceNote"].ToString();
            txt_closeReason.Text = dr["closeReason"].ToString();
            ext_receiveDt.SelectedDate = Convert.ToDateTime(dr["receiveDt"]);        //收货日期
            //ddl_receiveTime.SelectedValue = Convert.ToDateTime(dr["receiveDt"]).Hour.ToString();    //收货时间
            //ext_receiveTime.Value = Convert.ToDateTime(dr["receiveDt"]).ToShortTimeString();

            string time = Convert.ToDateTime(dr["receiveDt"]).Hour - 1 + ":00" + "-" + Convert.ToDateTime(dr["receiveDt"]).ToShortTimeString();

            ListItem c = ddl_receiveTime.Items.FindByText(time);

            if (c != null)
            {
                ddl_receiveTime.ClearSelection();
                c.Selected = true;
            }

            TimeSpan ts = Convert.ToDateTime(Convert.ToDateTime(dr["receiveDt"].ToString()).ToShortDateString()) - Convert.ToDateTime(DateTime.Now.ToShortDateString());
            if (ts.Days > 1 || dr["status"].ToString() != "6")
            //if (dr["status"].ToString() !="6" || Convert.ToDateTime(dr["receiveDt"].ToString()).ToShortDateString() != DateTime.Now.AddDays(+1).ToString("yyyy-MM-dd"))
            {
                btn_Save.Visible = false;
            }
            lbl_company.Text = dr["company"].ToString();
            lbl_contact.Text = dr["contact"].ToString();
            lbl_contactMobile.Text = dr["contactMobile"].ToString();
            lbl_contactPhone.Text = dr["contactPhone"].ToString();
            lbl_Address.Text = dr["address"].ToString();
            isUnderTransfer = dr["status"].ToString() == "6";
        }
        protected void btn_UpdateStatus_Click(object sender, EventArgs e)
        {
            logic.order.closeDynamicOrder(id, txt_closeReason.Text);
            logic.order.updateDynamiceOrderByOrderId(id, logic.sysAdmin.AdminID);
            Library.Script.ClientMsg("交易已关闭!");
            rptBind();
        }
        protected void btn_UpdateOrder_Click(object sender, EventArgs e)
        {
            TimeSpan ts = Convert.ToDateTime(ext_receiveDt.Value) - Convert.ToDateTime(DateTime.Now.ToShortDateString());
            int day = ts.Days;
            if (day>0)
            {
                OrderEntity _order = new OrderEntity();
                _order.Orderid = id;
                _order.ServiceNote = txt_serviceNote.Text;
                string timeRange = ddl_receiveTime.SelectedItem.Text;
                int hour = Convert.ToInt32(timeRange.Substring(timeRange.IndexOf("-") + 1, timeRange.Length - (timeRange.IndexOf("-") + 4)));
                _order.ReceiveDt = Convert.ToDateTime(ext_receiveDt.Value).AddHours(hour);
                _order.AdminId = logic.sysAdmin.AdminID;
                logic.order.updateDynamicOrderByService(_order);
                logic.order.updateDynamiceOrderByOrderId(id, _order.AdminId);
                if (day >= 2)
                {
                    Library.Script.ClientMsg("修改成功！");
                }
                else
                {
                    Library.Script.ClientMsg("您选择的时间为明天，请点击“生成正式订单”按钮生成正式订单!");
                    btn_Save.Visible = true;
                }
                //Coolite.Ext.Web.Ext.Msg.Alert("提示", "修改成功!");
                rptBind();
                getDetails(id);
                rtpDobind(id);
                dynamicorder_details.Show();
            }
            else
            {
                Library.Script.ClientMsg("收货时间必须在明天以后（包括明天）！");
                rptBind();
                getDetails(id);
                rtpDobind(id);
                dynamicorder_details.Show();
            }
        }
        protected void rtpDobind(int orderid)
        {
            StringBuilder where = new StringBuilder();
            where.Append("1=1");
            where.AppendFormat(" AND orderId={0}", orderid);
            DataSet ds = logic.order.selectDynamicOrderItem(where.ToString(), "inputDt", AspNetPager1.PageSize, AspNetPager1.CurrentPageIndex);
            rpt_DynamicOrderItems.DataSource = ds.Tables[1];
            rpt_DynamicOrderItems.DataBind();
        }
        protected void rpt_DynamicOrderItems_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            if (e.CommandName == "Del")
            {
                int oiid = Convert.ToInt32(e.CommandArgument.ToString());
                logic.orderItem.deleteDynamicOrderItem(oiid);
                logic.order.updateDynamiceOrderByOrderId(id, logic.sysAdmin.AdminID);
                Library.Script.ClientMsg("删除成功.");
                rptBind();
                getDetails(id);
                rtpDobind(id);
                dynamicorder_details.Show();
            }
            if (e.CommandName == "ReamrksEdit")
            {
                int oiid = Convert.ToInt32(e.CommandArgument.ToString());
                TextBox txtamount = (TextBox)e.Item.FindControl("txt_quantity");
                decimal quantity = Convert.ToDecimal(txtamount.Text.ToString());
                TextBox txtremarks = (TextBox)e.Item.FindControl("txtNote");
                string remarks = txtremarks.Text.ToString();
                logic.orderItem.updateDynamicOrderItemByOiid(oiid, remarks, quantity);
                logic.order.updateDynamiceOrderByOrderId(id, logic.sysAdmin.AdminID);
                rptBind();
                getDetails(id);
                rtpDobind(id);
                dynamicorder_details.Show();
            }
        }
        protected void btn_Save_Click(object sender, EventArgs e)
        {

            OrderEntity Dynamicorder = logic.order.getDynamicById(id);
            StringBuilder where = new StringBuilder();
            where.Append("1=1");
            where.AppendFormat(" AND orderId={0}", id);
            DataSet ds = logic.order.selectDynamicOrderItem(where.ToString(), "productId desc", AspNetPager1.PageSize, AspNetPager1.CurrentPageIndex);
            DataTable dt = ds.Tables[1];
            int errorno = 0;
            decimal amount = 0;
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                if (dt.Rows[i]["nowprice"].ToString() != "")
                {

                    amount = amount + Convert.ToDecimal(Convert.ToDouble(dt.Rows[i]["nowprice"].ToString()) * Convert.ToDouble(dt.Rows[i]["quantity"].ToString()));
                }
                else
                {
                    errorno++;
                    logic.orderItem.updateDynamicOrderItem(Convert.ToInt32(dt.Rows[i]["orderId"].ToString()), Convert.ToInt32(dt.Rows[i]["productId"].ToString()), dt.Rows[i]["businessnature"].ToString());
                }
            }
            OrderEntity order = Dynamicorder;
            order.TypeCount = Dynamicorder.TypeCount - errorno;
            order.Amount = Math.Round(amount,2, MidpointRounding.AwayFromZero);
            order.StandardAmount = order.Amount;
            order.OrderNo = "";
            order.Status = "1";
            int OrderId = logic.order.insertWithDynamicOrder(order);
            string OrderNo = logic.order.getById(OrderId).OrderNo;
            int adminId = logic.sysAdmin.AdminID;
            logic.order.updateDynamicOrder(id, OrderNo, adminId);
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                if (dt.Rows[i]["nowprice"].ToString() != "")
                {
                    OrderItemEntity oi = new OrderItemEntity();
                    oi = new OrderItemEntity();
                    oi.CustomerId = Convert.ToInt32(dt.Rows[i]["customerId"].ToString());
                    oi.SellerId = Convert.ToInt32(dt.Rows[i]["sellerId"].ToString());
                    oi.ProductId = Convert.ToInt32(dt.Rows[i]["productId"].ToString());
                    oi.Price = Convert.ToDecimal(dt.Rows[i]["nowprice"].ToString());
                    oi.SellerPrice = Convert.ToDecimal(dt.Rows[i]["sellerPrice"].ToString());
                    oi.Unit = dt.Rows[i]["unit"].ToString();
                    oi.Quantity = Convert.ToDecimal(dt.Rows[i]["quantity"].ToString());
                    oi.Note = dt.Rows[i]["note"].ToString();
                    oi.OrderId = OrderId;
                    oi.InitQuantity = oi.Quantity;
                    oi.BusinessNature = dt.Rows[i]["businessNature"].ToString();
                    logic.orderItem.insert(oi);
                }
            }
            logic.order.updateDynamiceOrderByOrderId(id, logic.sysAdmin.AdminID);
            rptBind();
            dynamicorder_details.Close();
        }

        protected void btn_Return_Click(object sender, EventArgs e)
        {
            dynamicorder_details.Close();

        }
        protected void lbn_Add_Click(object sender, EventArgs e)
        {
            categoryRootBind();
            categorySubBind();
            rptProBind();
        }
        void categoryRootBind()
        {
            int companyId = logic.order.getDynamicById(id).CompanyId;
            //ddl_CategoryRoot.DataSource = logic.category.listWithCompanyRange(companyId);
            ddl_CategoryRoot.DataSource = logic.buyerRange.rootCategorylistWithCompanyRange(companyId);
            ddl_CategoryRoot.DataBind();
            ddl_CategoryRoot.Items.Insert(0, new ListItem("-所有大类-", ""));
        }
        void categorySubBind()
        {
            if (ddl_CategoryRoot.SelectedValue != "")
            {
                int companyId = logic.order.getDynamicById(id).CompanyId;
                //DataTable dt = logic.category.getByParent(Convert.ToInt32(ddl_CategoryRoot.SelectedValue));
                DataTable dt = logic.buyerRange.subCategory_listWithCompanyRange(companyId, Convert.ToInt32(ddl_CategoryRoot.SelectedValue));
                ddl_CategorySub.DataSource = dt;
                ddl_CategorySub.DataBind();
                ddl_CategorySub.Items.Insert(0, new ListItem("-请选择小类-", ""));
            }
        }
        void rptProBind()
        {
            int companyId = logic.order.getDynamicById(id).CompanyId;
            StringBuilder where = new StringBuilder();
            //where.Append("categoryIsShow=1");
            where.Append("buyerId = " + companyId + " and categoryIsShow=1");
            if (ddl_CategoryRoot.SelectedValue != "")
                where.AppendFormat("and newCategoryId={0}", ddl_CategoryRoot.SelectedValue);
            //where.AppendFormat("and categoryParentId={0}", ddl_CategoryRoot.SelectedValue);
            if (ddl_CategorySub.SelectedValue != "")
                where.AppendFormat("and categoryId={0}", ddl_CategorySub.SelectedValue);
            if (txt_ProductNo.Text.Trim() != "")
                where.AppendFormat(" and productNo like '%{0}%'", txt_ProductNo.Text.Trim());
            if (txt_ProductName.Text.Trim() != "")
                where.AppendFormat(" and [Name] like '%{0}%'", txt_ProductName.Text.Trim());
            DataSet ds = logic.buyerRange.listWithPrice(where.ToString(), "productId", AspNetPager3.PageSize, AspNetPager3.CurrentPageIndex);
            //DataSet ds = logic.product.listWithCurrentPrice(Convert.ToInt32(hd_companyid.Value),
            //where.ToString(), "productId", AspNetPager2.PageSize, AspNetPager2.CurrentPageIndex);
            AspNetPager3.RecordCount = Convert.ToInt32(ds.Tables[0].Rows[0][0]);
            rpt_Products.DataSource = ds.Tables[1];
            rpt_Products.DataBind();
            product_add.Show();
        }
        protected void AspNetPager3_PageChanged(object sender, EventArgs e)
        {
            rptProBind();
        }
        protected void ddl_CategoryRoot_SelectedIndexChanged(object sender, EventArgs e)
        {
            categorySubBind();
        }
        protected void lbn_AddOrderItem_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < rpt_Products.Items.Count; i++)      //循环Repeater
            {
                RepeaterItem row = rpt_Products.Items[i];
                HiddenField hidproId = row.FindControl("hid_productId") as HiddenField;
                HiddenField hidsellerId = row.FindControl("hid_sellerId") as HiddenField;
                HiddenField hidsellerPrice = row.FindControl("hid_sellerPrice") as HiddenField;
                Label lblprice = row.FindControl("lbl_price") as Label;
                HiddenField lblnature = row.FindControl("hidNature") as HiddenField;
                TextBox txtQuantity = row.FindControl("txtQuantity") as TextBox;
                TextBox txtnote = row.FindControl("txtNote") as TextBox;
                CheckBox cbxUser = row.FindControl("cbx_isUser") as CheckBox;
                if (cbxUser.Checked)            //找到选择的商品加入数据库
                {
                    OrderItemEntity oi = new OrderItemEntity();
                    oi.CustomerId = logic.order.getDynamicById(id).CustomerId;
                    oi.Note = txtnote.Text; ;
                    oi.OrderId = id;
                    oi.Price = Convert.ToDecimal(lblprice.Text);
                    oi.ProductId = Convert.ToInt32(hidproId.Value);
                    oi.Quantity = Convert.ToDecimal(txtQuantity.Text);
                    oi.InitQuantity = oi.Quantity;
                    oi.BusinessNature = lblnature.Value;
                    PriceEntity pr = logic.price.getByProduct(oi.ProductId, lblnature.Value);
                    oi.SellerId = pr.CompanyId;
                    oi.SellerPrice = pr.SellerPrice;
                    oi.Unit = pr.Unit;
                    logic.orderItem.insertDynamicOrderItem(oi);
                }
            }
            logic.order.updateDynamiceOrderByOrderId(id, logic.sysAdmin.AdminID);
            rptBind();
            getDetails(id);
            rtpDobind(id);
            dynamicorder_details.Show();
        }
        protected void lbn_search_Click(object sender, EventArgs e)
        {
            AspNetPager3.CurrentPageIndex = 1;
            rptProBind();
        }
        protected void lbl_cancel_Click(object sender, EventArgs e)
        {
        }
    }
}
